#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>

#define TIME_DIFF(t1, t2) \
	((t2.tv_sec - t1.tv_sec) * 1000000 + (t2.tv_usec - t1.tv_usec))

#define N 1024

int board[N+2][N+2];
int num_neigh[N+1][N+1];

void usage(char * prog)
{
  printf("%s nb_iteration\n", prog);
}

void output_board(int board[N+2][N+2], int n, int loop) {
  int i,j;
  printf("loop %d\n", loop);
  for (i=1; i<n+1; i++) {
    for (j=1; j<n+1; j++) {
      if (board[i][j])
	putchar('X');
      else
	putchar('.');
    }
    putchar('\n');
  }
  sleep(1);
  int u = system("clear");
  u++;

}
int main(int argc, char* argv[]) {

  int i, j, loop, num_alive, maxloop;
  struct timeval t1, t2;
  unsigned long time;

  if (argc != 2){
    usage(argv[0]);
    return EXIT_FAILURE;
  }
  maxloop = atoi(argv[1]);
  num_alive = 0;

  for (i = 1; i <= N; i++) {
    for (j = 1; j <= N; j++) {
      if (i == N/2 || j == N/2) {
	board[i][j] = 1;
	num_alive ++;
      }
      else
	board[i][j] = 0;
    }
  }

  //Impression de la matrice initiale
  //output_board(board, N, 0);

  gettimeofday(&t1,NULL);

  for (loop = 1; loop <= maxloop; loop++) {

    board[0][0] = board[N][N];
    board[0][N+1] = board[N][1];
    board[N+1][0] = board[1][N];
    board[N+1][N+1] = board[1][1];

    for (i = 1; i <= N; i++) {
      board[i][0] = board[i][N];
      board[i][N+1] = board[i][1];
      board[0][i] = board[N][i];
      board[N+1][i] = board[1][i];
    }

    for (i = 1; i <= N; i++) {
      for (j = 1; j <= N; j++) {
   	num_neigh[i][j] = board[i][j+1] + board[i][j-1] +
	  board[i+1][j] + board[i-1][j] +
	  board[i+1][j+1] + board[i-1][j-1] +
	  board[i+1][j-1] + board[i-1][j+1];
      }
    }

    num_alive = 0;
    for (i = 1; i <= N; i++) {
      for (j = 1; j <= N; j++) {
	if (num_neigh[i][j] < 2 || num_neigh[i][j] > 3) 
	  board[i][j] = 0;
	else
	  if (num_neigh[i][j] == 3)
	    board[i][j] = 1;

	if (board[i][j] == 1) {
	  num_alive ++;
	}
      }
    }

    //output_board(board, N, loop);
    }

#ifdef PRINT_ALIVE
    printf("%d \n", num_alive);
#endif

  gettimeofday(&t2,NULL);
  time = TIME_DIFF(t1,t2);
  printf("time=%.2f\n",(float)time/1000);

  return EXIT_SUCCESS;
}

